package initializer

import (
	"context"
	"fmt"
	"go-caipu/pkg/infra/log"
	"go-caipu/pkg/plugins"
	"go-caipu/pkg/setting"
)

type Initializer struct {
	cfg             *setting.Cfg
	backendProvider plugins.BackendFactoryProvider
	log             log.Logger
}

func New(cfg *setting.Cfg, backendProvider plugins.BackendFactoryProvider) Initializer {
	return Initializer{
		cfg:             cfg,
		backendProvider: backendProvider,
		log:             log.New("plugin.initializer"),
	}
}

func (i *Initializer) Initialize(ctx context.Context, p *plugins.Plugin) error {
	i.log.Debug("Initializing plugins", "plugins", p.ID)
	if p.Backend {
		backendFactory := i.backendProvider.BackendFactory(ctx, p)
		if backendFactory == nil {
			return fmt.Errorf(" could not find backend factory for plugin")
		}

		if backendClient, err := backendFactory(p.ID, p.Logger(), i.envVars(p)); err != nil {
			return err
		} else {
			p.RegisterClient(backendClient)
		}
	}
	return nil
}

// envVars 初步使要传入插件的配置
func (i *Initializer) envVars(plugin *plugins.Plugin) []string {
	hostEnv := []string{
		fmt.Sprintf("CP_VERSION=%s", "v1.0.0"),
	}
	return hostEnv
}
